package org.qydjk.console.controller.company;

import org.elasticsearch.common.collect.HppcMaps;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.company.*;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.console.service.ICompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 企业产品
 * Created by Edward_yang on 2018/1/5 0005.
 */
@RequestMapping("/companyProduct")
@Controller
public class CompanyProductController extends BaseController {
    @Autowired
    private ICompanyService companyService;
     /***
     * @author Edward_yang
     * @uptime 2018-01-05
     * 企业产品管理跳转
     * @return
     */
    @RequestMapping("/gotoCompanyProduct.do")
    public String  gotoCompanyProduct(){
        return "/company/companyProductList";
    }

    /***
     *
     * @author Edward_yang
     * @uptime 2018-01-05
     * 企业产品显示
     * @return
     */
    @RequestMapping("/companyProductList.do")
    @ResponseBody
    public Object companyProductList(Integer page,Integer rows,String keyWord){
        HibernatePage pager = new HibernatePage(page,rows);
        String sql=" SELECT  qcp.id as  id , qcp.company_id as companyId , qcp.price , qc.name as companyName ,qcp.img as img, qc.type as type ,qcp.name as name , qcp.create_time as createTime, qcp.ord as ord"+
                " FROM  qy_company qc ,qy_company_product qcp " +
                " WHERE qc.id=qcp.company_id" ;
        String countSql="SELECT count(qcp.id) "+
                "  FROM  qy_company qc ,qy_company_product qcp " +
                " WHERE qc.id=qcp.company_id";
        if(!StringUtil.isEmptyOrNull(keyWord)){
            sql+="  and qcp.name like '%"+keyWord+"%' or  qc.name like '%"+keyWord+"%'";
            countSql+=" and qcp.name like '%"+keyWord+"%' or  qc.name like '%"+keyWord+"%'";
        }
        sql+="  ORDER BY  qcp.create_time desc";
        try {
            List<Map<String,Object>> productList=baseService.findMapBySQL(sql,pager);
            int total = baseService.getRecordCountSQL(countSql);
            return new EasyUIResponse(total,productList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /***
     *
     * @author Edward_yang
     * @uptime 2018-01-05
     * 增加产品
     */
    @RequestMapping("/add.do")
    @ResponseBody
    public Object addCompanyProduct(CompanyProduct companyProduct){
        if(companyProduct.getCompanyId()==null){
            return renderError("您输入企业不存在!");
        }
        companyProduct.setIssue(0);
        companyProduct.setThumbnailImg(companyProduct.getImg());
        companyProduct.setCreateTime(new Date());
        companyProduct.setUpdateTime(new Date());
        try {
            baseService.save(companyProduct);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }


    }
    /***
     *
     * @author Edward_yang
     * @uptime 2018-01-05
     * 修改产品
     */
    @RequestMapping("/edit.do")
    @ResponseBody
    public Object editCompanyProduct(CompanyProduct companyProduct){
        if(companyProduct.getCompanyId()==null){
            return renderError("您输入企业不存在!");
        }
        try {
            companyProduct.setThumbnailImg(companyProduct.getImg());
            CompanyProduct companyProduct1=baseService.get(CompanyProduct.class,companyProduct.getId());
            BeanUtil.copyProperties(companyProduct,companyProduct1);
            companyProduct1.setUpdateTime(new Date());
            baseService.saveOrUpdate(companyProduct1);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

    }

    /***
     *
     * @author Edward_yang
     * @uptime 2018-01-05
     * 删除产品
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteCompanyProduct(){
        return null;
    }


    /**
     * 获取单项库分类列表
     * @author Edward_yang
     * @uptime 2018-01-05
     */
    @RequestMapping("/singleProjectCategoryList.do")
    @ResponseBody
    public Object singleProjectCategoryList( Integer page,Integer rows,Integer companyProductId,String keyWord) {
        List<Map<String,Object>>   singleProjectCategoryList;//全部分类
        List<Map<String,Object>>   productSingleProjectCategoryList;//企业产品已配单项分类
        try {
            String sql = "SELECT  qspc.id as id , qspc.name as name ,qspc.ord as ord ,qspc.status as status FROM qy_single_project_category qspc WHERE qspc.status=1";
            String sql1="SELECT qcpc.single_project_category_id as  categoryId  FROM qy_company_product_category qcpc WHERE  company_product_id="+companyProductId;
            productSingleProjectCategoryList=  baseService.findMapBySQL(sql1);
            String countSql = "select count(qspc.id) from qy_single_project_category qspc";
            if(!StringUtil.isEmptyOrNull(keyWord)){
                sql+="  and qspc.name like '%"+keyWord+"%' ";
                countSql+=" and qspc.name like '%"+keyWord+"%'";
            }
            sql = sql + " order by ord desc";
            singleProjectCategoryList = baseService.findMapBySQL(sql,new HibernatePage(page, rows));
            for(Map map:singleProjectCategoryList){
                if (productSingleProjectCategoryList!=null&& productSingleProjectCategoryList.size()!=0){
                    outer: for(Map map1: productSingleProjectCategoryList){
                        if(map.get("id").toString().equals(map1.get("categoryId").toString())){
                            map.put("statusType",1);//已配置
                            map.put("type",1);//已配置
                            map.put("companyProductId",companyProductId);
                            break outer;
                        }else{
                            map.put("statusType",0);//未配置
                            map.put("type",0);//未配置
                            map.put("companyProductId",companyProductId);
                        }
                    }
                }else{
                    map.put("statusType",0);//未配置
                    map.put("type",0);//未配置
                    map.put("companyProductId",companyProductId);
                }
            }
            int total = baseService.getRecordCountSQL(countSql);
            return new EasyUIResponse(total, singleProjectCategoryList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /****
     * 点击配置单项分类(添加)
     * @author Edward_yang
     * @uptime 2018-01-05
     */
    @RequestMapping("/checkConfiguration.do")
    @ResponseBody
    public Object checkConfiguration(Integer companyProductId,Integer singleProjectCategoryId){
        CompanyProductCategory companyProductCategory=new CompanyProductCategory();
        companyProductCategory.setCompanyProductId(companyProductId);
        companyProductCategory.setSingleProjectCategoryId(singleProjectCategoryId);
        companyProductCategory.setCreateTime(new Date());
        companyProductCategory.setUpdateTime(new Date());
        try {
            baseService.save(companyProductCategory);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /***
     * 取消配置分类(删除)
     * @author Edward_yang
     * @uptime 2018-01-05
     * @return
     */
    @RequestMapping("/deletecheckConfiguration.do")
    @ResponseBody
    public Object deletecheckConfiguration(Integer companyProductId,Integer singleProjectCategoryId){
        try {
            List<CompanyProductSingleProject>  ProductSingleProjectList=baseService.findBeanBySQL("SELECT *FROM qy_company_product_single_project  WHERE company_product_id="+companyProductId+" and single_project_category_id="+singleProjectCategoryId,CompanyProductSingleProject.class);
            if(ProductSingleProjectList.size()>0){
                return renderError("请取消分类下的单项的配置");
            }
            baseService.excuteSQL("DELETE FROM qy_company_product_category WHERE company_product_id="+companyProductId+" and single_project_category_id="+singleProjectCategoryId);//删除那一条数据
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }

    /**
     * 自动补全 商家用户信息
     *
     * @author Edward_yang
     * @uptime 2018-01-05
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object companyProductAutoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        String query = request.getParameter("query");
        if (StringUtil.isEmptyOrNull(query)) {
            return new AutoCompleteResponse(list);
        }
        String sql = "SELECT concat(name) AS `value`,concat(id,'') AS `data` FROM qy_company WHERE   name LIKE '%" + query + "%'";
        try {
            list = baseService.findBeanBySQL(sql, AutoCompleteBean.class, new HibernatePage(1, 10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }


    /**
     * 获取产品单项列表
     * @author Edward_yang
     * @uptime 2018-01-08
     */
    @RequestMapping("/productSingleProjectList.do")
    @ResponseBody
    public Object productSingleProjectList( Integer page,Integer rows,Integer companyProductId,Integer categoryId,String keyWord) {
        List<Map<String,Object>>   singleProjectList;//全部单项
        List<Map<String,Object>>   productSingleProjectList;//产品已配单项
        try {
            String sql = "SELECT  qsp.id as id , qsp.single_project_category_id as singleProjectCategoryId ,qsp.name as name,qsp.price as price,qsp.des as des,qsp.significance as significance,qsp.ord as ord ,qsp.status as status FROM qy_single_project qsp  WHERE   qsp.single_project_category_id="+categoryId;
            String sql1="SELECT qcpsp.single_project_id as  singleProjectId  FROM qy_company_product_single_project qcpsp WHERE qcpsp.company_product_id="+companyProductId;
            productSingleProjectList= baseService.findMapBySQL(sql1);
            String countSql = "select count(id) from qy_single_project_category";

            if(!StringUtil.isEmptyOrNull(keyWord)){
                sql+="  and qsp.name like '%"+keyWord+"%' ";
                countSql+=" and qsp.name like '%"+keyWord+"%'";
            }
            sql = sql + " order by ord desc";
            singleProjectList = baseService.findMapBySQL(sql, new HibernatePage(page, rows));
            for(Map map:singleProjectList){
                if (productSingleProjectList!=null&& productSingleProjectList.size()!=0){
                    outer: for(Map map1: productSingleProjectList){
                        if(map.get("id").toString().equals(map1.get("singleProjectId").toString())){
                            map.put("statusType",1);//已配置
                            map.put("type",1);//已配置
                            map.put("companyProductId",companyProductId);
                            break outer;
                        }else{
                            map.put("statusType",0);//未配置
                            map.put("type",0);//未配置
                            map.put("companyProductId",companyProductId);
                        }
                    }
                }else{
                    map.put("statusType",0);//未配置
                    map.put("type",0);//未配置
                    map.put("companyProductId",companyProductId);
                }
            }
            int total = baseService.getRecordCountSQL(countSql);
            return new EasyUIResponse(total, singleProjectList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /****
     * 点击配置单项(添加)
     * @author Edward_yang
     * @uptime 2018-01-08
     * @return
     */
    @RequestMapping("/checkSingleProject.do")
    @ResponseBody
    public Object checkSingleProject(Integer companyProductId,Integer singleProjectCategoryId,  Integer singleProjectId){
        try {
            String sql="SELECT qcpc.single_project_category_id as  categoryId  FROM qy_company_product_category qcpc " +
                    "WHERE  qcpc.company_product_id="+companyProductId+" and qcpc.single_project_category_id="+singleProjectCategoryId;
            List<Map<String,Object>>   productSingleProjectCategoryList;//产品已配单项分类
            productSingleProjectCategoryList=baseService.findMapBySQL(sql);
            if(productSingleProjectCategoryList.size()<=0){
                return renderError("请配置该单项的分类");
            }
            CompanyProductSingleProject companyProductSingleProject=new   CompanyProductSingleProject();
            companyProductSingleProject.setCompanyProductId(companyProductId);
            companyProductSingleProject.setSingleProjectId(singleProjectId);
            companyProductSingleProject.setSingleProjectCategoryId(singleProjectCategoryId);
            companyProductSingleProject.setCreateTime(new Date());
            companyProductSingleProject.setUpdateTime(new Date());
            baseService.save(companyProductSingleProject);
            changeprice(companyProductId); //更新参考价
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
    }
    /***
     *取消配置单项(删除)
     * @author Edward_yang
     * @uptime 2018-01-08
     * @return
     */
    @RequestMapping("/deleteCheckSingleProject.do")
    @ResponseBody
    public Object deleteCheckSingleProject(Integer companyProductId,Integer singleProjectId){
        try {
            baseService.excuteSQL("DELETE FROM qy_company_product_single_project WHERE company_product_id="+companyProductId+" and single_project_id="+singleProjectId);//删除那一条数据
            changeprice(companyProductId); //更新参考价
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return  renderError(e.getMessage());
        }
    }

    /***
     * 发布企业产品
     * @author Edward_yang
     * @uptime 2018-01-08
     * @return
     */
    @RequestMapping("/publishCompanyPoudct.do")
    @ResponseBody
    public Object publishCompanyPoudct(InviteRecord inviteRecord){
        try {
            inviteRecord.setPublishTime(new Date());
            companyService.putPublish(inviteRecord);
            return renderSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("系统错误，请联系管理员");
        }
    }
    /*机构备选*/
    @RequestMapping("/getSells.do")
    @ResponseBody
    public Object getSells(){
        try {
            String query = request.getParameter("query");
            query = StringUtil.iosToUTF8(query).trim();
            if("".equals(query)){return null;}
            System.out.println("-----------------------"+query);
            String companyId = request.getParameter("companyId");
            Company company = baseService.get(Company.class,Integer.parseInt(companyId));
            int city = company.getCity();
            List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
            if (StringUtil.isEmptyOrNull(query)) {
                return new AutoCompleteResponse(list);
            }
            String sql = "select name as value,concat(id,'') as data from qy_seller where two_area_id="+city+" and name like '%"+query+"%'";
            list = baseService.findBeanBySQL(sql, AutoCompleteBean.class, new HibernatePage(1, 10));
            return new AutoCompleteResponse(list);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.toString());
        }
    }
    @RequestMapping("/cbCategory.do")
    @ResponseBody
    public Object cbCategory(String sellerProductLabelCode){
        List<Map<String,Object>> list =  new ArrayList<Map<String,Object>>();
        try {
            String sql="select id,name from qy_seller_product_label_detail where seller_product_label_code='"+sellerProductLabelCode+"'";
            list =baseService.findMapBySQL(sql);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.toString());
        }
    }

    /**
     *更新参考价格
     * @param companyProductId
     * @return
     */
    public int changeprice(Integer companyProductId){
        try {
            String singsql = "select sum(s.price) as price from qy_company_product_single_project c,qy_single_project s " +
                    "where c.single_project_id = s.id and c.company_product_id = "+companyProductId;
            List<Map<String,Object>> pricemap = baseService.findMapBySQL(singsql);
            CompanyProduct product = baseService.get(CompanyProduct.class,companyProductId);
            product.setPrice((BigDecimal) pricemap.get(0).get("price"));
            baseService.saveOrUpdate(product);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}
